import os
import logging
from logging.handlers import RotatingFileHandler
from src.utils.config_utils import DataConfigParser


class _LogHelper(object):
    _inst = None
    
    _logger = None
    _fileHandler = None
    _fmtr = None
    _consoleHandler = None

    def __new__(cls):
        if cls._inst is None:
            cls._inst = object.__new__(cls)

            cls._logger = logging.getLogger('GlobalPoint5DownScaling')
            cls._logger.setLevel(logging.INFO)
            cls._fmtr = logging.Formatter('%(asctime)s [%(process)s] %(levelname)s %(message)s')

            # log to console
            cls._consoleHandler = logging.StreamHandler()
            cls._consoleHandler.setLevel(logging.INFO)
            cls._consoleHandler.setFormatter(cls._fmtr)

        return cls._inst

    def set_log(self):
        # log to file
        log_path = os.path.join(os.path.abspath(os.getcwd()), 'logs')
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        log_path = os.path.join(log_path, 'GlobalPoint5DownScaling' + '.log')
        log_file_max_bytes = DataConfigParser().get_data_configuration("logFile", "log_file_max_bytes")

        self._fileHandler = RotatingFileHandler(log_path, maxBytes=int(log_file_max_bytes) * 1024 * 1024, backupCount=20)
        self._fileHandler.setLevel(logging.INFO)
        self._fileHandler.setFormatter(self._fmtr)

    def _loadHdlr(self, loadfhdlr, loadchdlr):
        if loadfhdlr:
            try:
                self._logger.addHandler(self._fileHandler)
            except:
                pass
        if loadchdlr:
            try:
                self._logger.addHandler(self._consoleHandler)
            except:
                pass
        
    def _unloadHdlr(self, unloadfhdlr, unloadchdlr):
        if unloadfhdlr:
            try:
                self._logger.removeHandler(self._fileHandler)
            except:
                pass
        if unloadchdlr:
            try:
                self._logger.removeHandler(self._consoleHandler)
            except:
                pass
    
    def release(self):
        self._fileHandler.close()
        self._consoleHandler.close()
    
    def info(self, message, filer=True, console=True):
        try:
            self._loadHdlr(filer, console)
            self._logger.info(message)
            self._unloadHdlr(filer, console)
        except:
            pass
    
    def warning(self, message, filer=True, console=True):
        try:
            self._loadHdlr(filer, console)
            self._logger.warning(message)
            self._unloadHdlr(filer, console)
        except:
            pass

    def error(self, message, filer=False, console=True):
        try:
            self._loadHdlr(filer, console)
            self._logger.error(message)
            self._unloadHdlr(filer, console)
        except:
            pass

logHelper = _LogHelper()

